﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WordSmith_V1.Library.Model.EntityFrameWork;
using WordSmith_V1.ViewModel;
using WordSmith_V1.Library.Model;

namespace WordSmith_V1.Controllers
{
    public class ChapterController : Controller
    {
        private WordSmithContext DB = new WordSmithContext();

        [HttpGet]
        public ActionResult Create(int bookId)
        {
            BookChapterCreateViewModel viewModel = new BookChapterCreateViewModel();
            var genres = DB.Genres.Where(gen => gen.Id >= 1).ToList();
            IEnumerable<SelectListItem> dropdownGenres = genres.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name.ToString() });
            ViewBag.genreList = dropdownGenres;//viewModel.Genres;
            viewModel.authorId = bookId;
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Create(BookChapterCreateViewModel viewModel)
        {

            try
            {
                string userEmail = HttpContext.User.Identity.Name;
                var user = DB.Users.Where(usr => usr.Email == userEmail).Take(1).ToList().FirstOrDefault();
                if (user != null)
                {
                    viewModel.Author = user;

                    string s = viewModel.Description;
                    int bkId = Int32.Parse(Request.QueryString.Get("bookId"));
                    var bk = DB.Books.Where(usr => usr.BookId == bkId).Take(1).ToList().FirstOrDefault();

                    Chapter chp = CreateChapter(viewModel, user.Id);
                    chp.BookId = bk.BookId;
                    //Add new book with new chapter                                      
                   // Book newBk = new Book();
                    bk.Chapters.Add(chp);
                   // DB.Books.Add(newBk);
                    DB.SaveChanges();
                    // int newBkID = newBk.BookId;
                    // add book's chapter
                    //chp.BookId = newBkID;
                    //DB.Chapters.Add(chp);
                    //DB.SaveChanges();
                    int newChpID = chp.ChapterId;
                    //add chapter tags
                    CreateAndSaveTags(newChpID, viewModel.Tags);

                    //index is like the summary page
                    return RedirectToActionPermanent("Index", "Book", new { bookId = bk.BookId });
                }
                return View(viewModel);
            } 
            catch
            {
                return new EmptyResult();
            }
            
        }



        private Chapter CreateChapter(BookChapterCreateViewModel viewModel, int userId)
        {
            Chapter chp = new Chapter();
            chp.Description = viewModel.Description;
            chp.Title = viewModel.ChapterTitle;
            chp.Writing = viewModel.Writing;
            chp.AuthorId = userId;
            chp.CoverImage = viewModel.CoverImage ?? "";
            chp.EmailMe = true;
            chp.CreateDate = DateTime.Now;
            chp.UpdateDate = DateTime.Now;
            chp.StatusId = (int)Status.StatusType.PENDING;
            return chp;
        }

        private void CreateAndSaveTags(int chapterId, string tagStr)
        {
            char[] delimiter = { ',' };
            string[] tags = tagStr.Split(delimiter);
            foreach (var tag in tags)
            {
                Tag newTag = new Tag(chapterId, tag);
                DB.Tags.Add(newTag);
                DB.SaveChanges();
            }

        }
    }
}